package com.example.certificate.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.certificate.dto.OrderCarDTO;
import com.example.certificate.dto.UpProductDTO;
import com.example.certificate.entity.OrderCart;
import com.example.certificate.entity.ProductInfo;
import com.example.certificate.entity.User;
import com.example.certificate.mapper.OrderCartMapper;
import com.example.certificate.mapper.ProductInfoMapper;
import com.example.certificate.service.OrderCartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.certificate.utils.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hao
 * @since 2022-03-10 12:25:41
 */
@Service
public class OrderCartServiceImpl extends ServiceImpl<OrderCartMapper, OrderCart> implements OrderCartService {


    @Resource
    private ProductInfoMapper productInfoMapper;


    @Resource
    private OrderCartMapper orderCartMapper;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 加入购物车
     *
     * @param carDTO
     */
    @Override
    public void addOrderCar(OrderCarDTO carDTO, User user) {

        OrderCart car = orderCartMapper.selectOne(new QueryWrapper<OrderCart>().eq("user_id", user.getId())
                .eq("product_info_id", carDTO.getProductId())
                .eq("price", carDTO.getPrice()));

        if(car != null){
            car.setTotalPrice(car.getTotalPrice() + carDTO.getTotalPricet());
            car.setProductAmount(car.getProductAmount() + carDTO.getProductAmount());
            orderCartMapper.updateById(car);
        }else {
            //添加商品到购物车
            OrderCart orderCart=new OrderCart();
            orderCart.setUserId(user.getId()); //用户ID
            orderCart.setPrice(carDTO.getPrice()); //商品价格
            orderCart.setTradeName(carDTO.getTradeName());
            orderCart.setProductInfoId(carDTO.getProductId()); //商品ID
            orderCart.setProductAmount(carDTO.getProductAmount()); //商品数量
            orderCart.setTotalPrice(carDTO.getTotalPricet());
            orderCartMapper.insert(orderCart); //添加
        }
    }

    /**
     * 修改购物车数量
     *
     * @param dto
     * @param user
     */
    @Override
    public void updateCar(OrderCarDTO dto, User user) {
        OrderCart car = orderCartMapper.selectById(dto.getProductId());
        //查询要修改的商品的信息
        car.setTotalPrice(car.getPrice() * dto.getProductAmount());
        car.setProductAmount(dto.getProductAmount()); //设置数量
        this.updateById(car); //修改
    }

    /**
     * 使用分页查询用户购物车
     *
     * @param user
     * @return
     */
    @Override
    public Page<OrderCart> selOrderCar(Page<OrderCart> page, User user) {
        page = orderCartMapper.selectPage(page,new QueryWrapper<OrderCart>().eq("user_id",user.getId()).orderByDesc("create_time"));
        page.getRecords().forEach(item->{
            //查询商品信息
           ProductInfo productInfo= productInfoMapper.selectOne(new QueryWrapper<ProductInfo>().eq("id",item.getProductInfoId()));
            if(productInfo != null){
                item.setTradeName(productInfo.getTradeName()); //商品名
                item.setTradePrice(productInfo.getTradePrice()); //商品价格
                item.setImageUrl(productInfo.getImage());
                if(StringUtils.hasLength(productInfo.getTradeDescribe())){
                    item.setTradeDescribe(productInfo.getTradeDescribe());
                }
                Boolean isMember = redisTemplate.opsForSet().isMember("favorite:" + user.getId(), productInfo.getId());
                item.setIsMember(isMember);
                item.setChecked(false);
            }
        });
        return page;
    }

    /**
     * 使用分页查询用户购物车
     *
     * @return
     */
    @Override
    public ResultEntity selOrderCarDetail(String ids) {
        String[] split = ids.split(",");
        List<OrderCart> orderCarts = orderCartMapper.selectList(new QueryWrapper<OrderCart>().in("id", split));
        orderCarts.forEach(item->{
            //查询商品信息
            ProductInfo productInfo= productInfoMapper.selectOne(new QueryWrapper<ProductInfo>().eq("id",item.getProductInfoId()));
            if(productInfo != null){
                item.setTradeName(productInfo.getTradeName()); //商品名
                item.setTradePrice(productInfo.getTradePrice()); //商品价格
                item.setImageUrl(productInfo.getImage());
                if(StringUtils.hasLength(productInfo.getTradeDescribe())){
                    item.setTradeDescribe(productInfo.getTradeDescribe());
                }
                item.setChecked(true);
            }
        });
        return new ResultEntity(orderCarts);
    }

    /**
     * 用户删除购物车数据
     *
     * @param dto
     * @param user
     */
    @Override
    public void delProduct(OrderCarDTO dto, User user) {
        orderCartMapper.delete(new QueryWrapper<OrderCart>().eq("id",dto.getProductId()));
    }

    /**
     * 修改用户购物车数量
     *
     * @param dto
     * @param user
     */
    @Override
    public void upCustomer(UpProductDTO dto, User user) {

        String temp = dto.getCustomerInfo();
        JSONArray jsonArray = JSONArray.parseArray(temp);
        for (int i = 0; i < jsonArray.size(); i++) {
            String id = (String) jsonArray.getJSONObject(i).get("id");
            Integer num = (Integer) jsonArray.getJSONObject(i).get("num");
            OrderCart orderCart = orderCartMapper.selectOne(new QueryWrapper<OrderCart>().eq("id",id)
                    .eq("user_id",user.getId()));
            if(orderCart!=null){
                orderCart.setProductAmount(num);
                this.updateById(orderCart);
            }
        }
    }
}
